'use strict';
import React, { createClass, PropTypes } from 'react'
import $ from 'jquery'
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import { requestQuestionsData, restoreQuestionsData } from '../actions'
import QuestionCard from '../components/QuestionCard'
import * as Common from '../util/Common'

let totalNum = 0;
const TestPaper = withRouter(createClass({
    getInitialState() {
        return {
            uiReady: false,
            topBarHeight: 0,
            bottomBarHeight: 0,
            testViewHeight: 0,
            currentCardIndex: 0
        }
    },
    componentDidMount() {
        const { params, dispatch, questionReducer } = this.props;
        let qid = params.id;

        if(questionReducer) {
            if(questionReducer.data && questionReducer.data.key == qid) {
                dispatch(restoreQuestionsData(questionReducer));
            }
            else {
                dispatch(requestQuestionsData(qid));
            }
        }
    },
    componentDidUpdate(nextProps, nextState) {
        // 如果界面没有准备好时，需要计算出测试界面的尺寸
        if (nextState.uiReady == false && this.refs.topBar != undefined) {
            let testViewHeight = $(window).height() - this.refs.topBar.offsetHeight - this.refs.bottomBar.offsetHeight;
            this.setState({
                uiReady: true,
                topBarHeight: this.refs.topBar.offsetHeight,
                bottomBarHeight: this.refs.bottomBar.offsetHeight,
                testViewHeight: testViewHeight
            });
        }
    },
    render: function () {
        const { questionReducer } = this.props;
        if (questionReducer) {
            if (questionReducer.loading) {
                return (<div className="loading">
                    <div className="spinner"></div>
                </div>)
            }
            else if (questionReducer.status) {
                let queObj = questionReducer.data,
                    listData = queObj.data,
                    queTitle = queObj.title;
                Common.setTitle(queTitle);
                let listLoading = '';
                let layoutList;
                totalNum = listData.length;

                if (this.state.uiReady) {
                    let winWidth = $(window).width();
                    let listStyles = {
                        position: 'relative',
                        height: this.state.testViewHeight + 'px',
                        overflow: 'hidden'
                    };
                    layoutList = <ul className="list question-list" style={listStyles}>
                        {
                            listData.map((item, idx) => {
                                let left = winWidth * (idx - this.state.currentCardIndex);
                                let qCardStyles = {
                                    position: 'absolute',
                                    top: 0,
                                    left: left,
                                    height: this.state.testViewHeight + 'px',
                                    overflow: 'auto'
                                };
                                return (
                                    <QuestionCard className="question-card" next={this.next.bind(this, idx+1)}
                                                  data={item} key={idx} index={idx}
                                                  elmStyle={qCardStyles}/>
                                );
                            })
                        }
                        {listLoading}
                    </ul>
                }
                else {
                    layoutList = <div className="loading">
                        <div className="spinner"></div>
                    </div>
                }

                let prevBtn, nextBtn;
                if (this.state.currentCardIndex === 0) {
                    //prevBtn = <a className="col-xs-6 btn-flat btn-prev-question" disabled>上一题</a>
                    prevBtn = '';
                }
                else {
                    let idx = 0;
                    if (this.state.currentCardIndex > 0) {
                        idx = this.state.currentCardIndex - 1;
                    }
                    prevBtn = <a className="col-xs-6 btn-flat btn-prev-question"
                                 onClick={this.goToCard.bind(this, idx)}>上一题</a>
                }
                if (this.state.currentCardIndex === parseInt(totalNum - 1)) {
                    nextBtn = <a className="col-xs-6 btn-flat btn-next-question" onClick={this.testResult}>提交</a>
                }
                else {
                    let idx = totalNum - 1,
                        nextBtnClsName = 'col-xs-6 btn-flat btn-next-question';
                    if (this.state.currentCardIndex < idx) {
                        idx = this.state.currentCardIndex + 1;
                    }
                    if (this.state.currentCardIndex === 0) {
                        nextBtnClsName = 'col-xs-12 btn-flat btn-next-question';
                    }
                    else {
                    }
                    nextBtn = <a className={nextBtnClsName} onClick={this.goToCard.bind(this, idx)}>下一题</a>
                }

                let pStyle = {
                    width: (parseInt((this.state.currentCardIndex + 1) / totalNum * 100000) / 1000) + '%'
                };

                return (<div className="test-paper">
                    <div className="top-bar" ref="topBar">
                        <nav>
                            <a href="javascript:;" onClick={this.back}>
                                <i className="glyphicon glyphicon-menu-left"></i>
                            </a>
                        </nav>
                        <div className="wrap">
                            <div className="metas">
                                <div className="meta">进度：<strong
                                    className="index-number">{this.state.currentCardIndex + 1} / {totalNum}</strong>
                                </div>
                            </div>
                            <div className="progress-bar" style={pStyle}></div>
                        </div>
                    </div>
                    {layoutList}
                    <div className="bottom-bar" ref="bottomBar">
                        <div className="btn-wrap row">
                            {prevBtn}
                            {nextBtn}
                        </div>
                    </div>
                </div>)
            }
            else {
                let errorMessage = questionReducer.error || '网络不可用';
                return <div className="load-error">{errorMessage}</div>
            }
        }
        else {
            return <div className="load-error">页面加载失败，点击重新加载...</div>
        }
    },
    goToCard: function (idx) {
        this.setState({
            currentCardIndex: idx
        });
    },
    next: function (idx) {
        if (idx > 0) {
            if (idx <= parseInt(totalNum - 1)) {
                this.goToCard(idx);
            }
            else {
                this.testResult();
            }
        }
    },
    back: function () {
        //window.history.go(-1);
        this.props.router.push({
            pathname: '/'
        });
    },
    testResult: function () {
        const { params, router } = this.props;
        let qid = params.id;
        router.push({
            pathname: '/test_result/'+qid
        });
    }
}));

const mapStateToProps = (state) => {
    const { questionReducer, optionReducer } = state;
    return {
        questionReducer,
        optionReducer
    }
};

export default connect(mapStateToProps)(TestPaper);